package com.beyondsoft.mcms.service;

import java.util.Iterator;
import java.util.List;

import javax.persistence.PersistenceException;

import org.springframework.transaction.annotation.Transactional;

import com.beyondsoft.mcms.common.Constants;
import com.beyondsoft.mcms.common.UmsApiServiceImpl;
import com.beyondsoft.mcms.domain.Advice;
import com.beyondsoft.mcms.domain.Attendee;
import com.beyondsoft.mcms.domain.Conference;
import com.beyondsoft.mcms.domain.Item;
import com.beyondsoft.mcms.domain.MemberInfo;

public class AttendeeServiceImpl implements AttendeeService {

	public void deleteAttendees(Advice advice) {
		Conference conference = advice.getConference();
		MemberInfo memberInfo = advice.getMemberInfo();
		List<Attendee> attendees = Attendee.findAttendeesByConferenceAndMemberInfo(memberInfo, conference)
				.getResultList();

		for (Iterator<Attendee> it = attendees.iterator(); it.hasNext();) {
			it.next().remove();
		}
	}

	@Transactional
	public void saveAttendees(Advice advice, List<Attendee> attendees) {
		if (advice != null) {
			deleteAttendees(advice);
		}

		for (Iterator<Attendee> it = attendees.iterator(); it.hasNext();) {
			Attendee attendee = it.next();
			List<Attendee> existed = Attendee.findAttendeesByConferenceAndMemberInfoAndAttendNameEquals(
					attendee.getConference(), attendee.getMemberInfo(), attendee.getAttendName()).getResultList();

			if (existed != null && existed.size() > 0) {
				for (Iterator<Attendee> itr = existed.iterator(); itr.hasNext();) {
					itr.next().remove();
				}
			}
			if (Attendee.countAttendes(attendee.getConference(), null) >= attendee.getConference().getMaxEntries()) {
				throw new PersistenceException("conference_field_attendee_full");
			}

			attendee.persist();
		}
	}

	public void batchSigning(String[] ids) {

		for (int i = 0; i < ids.length; i++) {
			Attendee attendee = Attendee.findAttendee(Long.valueOf(ids[i]));
			if (attendee != null) {
				attendee.setAttendStatus(Item.findItem(Constants.ATTENDEE_STATUS_SIGNED));
				attendee.merge();
			}
		}
	}
	
	public void smSending(String smsIds, String sms) {
		String phonesNo = "";
		String[] ids = smsIds.split(",");
		for (int i = 0; i < ids.length; i++) {
			Attendee attendee = Attendee.findAttendee(Long.valueOf(ids[i]));
			if (attendee != null) {
				String phoneNo = attendee.getAttendMobilePhone();
				phonesNo += phoneNo + ",";
			}
		}
		
		try{
			UmsApiServiceImpl.sendShortMsgByPost(sms, phonesNo.substring(0, phonesNo.length()-1));

		}catch(Exception e){
			
		}
	}

}
